package org.test.xml;

import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Date;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import org.junit.Before;
import org.junit.Test;
import org.test.domain.Measure;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;

public class JaxbExample {

    private JAXBContext jaxbContext;

    @Before
    public void setUp() throws Exception {
        this.jaxbContext = JAXBContext.newInstance(Measure.class);
    }

    protected String marshall(Measure measure) throws JAXBException {
        StringWriter writer = new StringWriter();
        this.jaxbContext.createMarshaller().marshal(measure, writer);
        return writer.toString();
    }

    protected Measure unmarshall(String measureAsXmlString) throws JAXBException {
        Reader reader = new StringReader(measureAsXmlString);
        Measure measure = (Measure) this.jaxbContext.createUnmarshaller().unmarshal(reader);
        return measure;
    }

    @Test
    public void testXmlMarshallAndUnmarshall() throws JAXBException {
        Measure measure = new Measure();
        measure.setModuleName("Test");
        measure.setName("testClientPostMeasure");
        long time = new Date().getTime();
        measure.setStartTime(time - 1000L);
        measure.setEndTime(time);
        String measureAsXmlString = marshall(measure);
        Measure unmarshalledMeasure = unmarshall(measureAsXmlString);
        assertNotSame(measure, unmarshalledMeasure);
        assertEquals(measure.getModuleName(), unmarshalledMeasure.getModuleName());
        assertEquals(measure.getName(), unmarshalledMeasure.getName());
        assertEquals(measure.getStartTime(), unmarshalledMeasure.getStartTime());
        assertEquals(measure.getEndTime(), unmarshalledMeasure.getEndTime());
        assertEquals(measure.isHasError(), unmarshalledMeasure.isHasError());
    }
}
